var SmartTable = {
	tabHeight: 300,
	isLoad: false,
	clearParams: function() {
		delete SmartTable.active;
		delete SmartTable.funId;
		delete SmartTable.paramNameVal;
		delete SmartTable.funGroupId;
		delete SmartTable.tableData;
		delete SmartTable.chartConfHtml;
	},
	previewTable: function() {
		var target = $(SmartTable.chartConfHtml);

		var path = SmartTable.path;
		$.get(path + 'chart_config.html', function(html) {
			var $html = $(html);

			var addChartParam = $html.find('#addChartParam');
			var configTable = $html.find('#chartConfigArea table');
			var chartTabConLine = $html.find('#chartTabConLine table tr');
			var showRightYAxis = $html.find('#showRightYAxis');
			var rightYAxisArea = $html.find('#rightYAxisArea');

			var columnInfos = SmartTable.tableData.columnInfos;

			// 添加chart配置行
			function appendChartCnfLine(chartLineParam) {
				var chartTabConLineClone = chartTabConLine.clone();

				var colName = chartLineParam.colName;
				var axisName = chartLineParam.axisName;
				var axisOption = chartLineParam.axisOption;

				// 添加数据列
				var colNames = chartTabConLineClone.find('select[name="colNames"]');
				for (var i = 0; i < columnInfos.length; i++) {
					var name = columnInfos[i].name;
					var option = $('<option ' + (name == colName ? 'selected' : '') + ' value="' + name + '">' + name + '</option>');
					colNames.append(option);
				}

				// 添加名称
				if (axisName) {
					chartTabConLineClone.find('input[name="axisName"]').val(axisName);
				}

				// 定位轴坐标
				if (axisOption) {
					chartTabConLineClone.find('select[name="axisOption"]').val(axisOption);
				}

				// 删除按钮事件
				var delLine = chartTabConLineClone.find('button[name="delLine"]');
				delLine.on('click', function() {
					var tr = $(this).parent().parent();
					tr.remove();
				});
				configTable.append(chartTabConLineClone);
			}

			// 填充XAxis数据
			var xAxisEle = $html.find('#xAxis');
			for (var i = 0; i < columnInfos.length; i++) {
				var name = columnInfos[i].name;
				var option = $('<option value="' + name + '">' + name + '</option>');
				xAxisEle.append(option);
			}

			// 填充数据
			if (SmartTable.active == 'double') {
				var chartConf = SmartTable.chartConf,
					chartLineParams = chartConf.chartLineParams,
					chartType = chartConf.chartType,
					xAxisColName = chartConf.xAxis.colName,
					leftYAxisName = chartConf.leftYAxis.name,
					isShowRightYAxis = chartConf.isShowRightYAxis,
					rightYAxisName = chartConf.rightYAxis.name;

				for (var i = 0; i < chartLineParams.length; i++) {
					appendChartCnfLine(chartLineParams[i]);
				}
				$html.find('#chartType').val(chartType);
				$html.find('#xAxis').val(xAxisColName);
				$html.find('#leftYAxisName').val(leftYAxisName);
				if (isShowRightYAxis) {
					showRightYAxis.prop('checked', isShowRightYAxis);
					$html.find('#rightYAxisName').val(rightYAxisName);
					rightYAxisArea.show();
				}
			}

			addChartParam.on('click', function() {
				appendChartCnfLine({});
			});

			showRightYAxis.on('change', function() {
				var val = $(this).prop('checked');
				if (val) {
					rightYAxisArea.show();
				} else {
					rightYAxisArea.hide();
					$html.find('#rightYAxisName').val('');
				}
			});

			target.html($html);
		})
	},
	getDialogParam: function(target) {
		var selectFunGroup = $('#funGroupId option:selected', target);
		SmartTable.funGroupId = selectFunGroup.val() + '-' + selectFunGroup.text();

		var selectFunsId = $('#funsId option:selected', target);
		SmartTable.funId = selectFunsId.data('data').id;
		SmartTable.paramNameVal = [];

		$('#funParamTableBody tr', target).each(function(i, n) {
			var $_tr = $(n);
			var name = $_tr.find('td:first').text();
			var val = $_tr.find('td:last option:selected').val();
			SmartTable.paramNameVal.push(name + '@' + val);
		});
	},
	getDialogChartParam: function(target) {
		var chartConf = {};
		chartConf.xAxis = {},
			chartConf.leftYAxis = {},
			chartConf.rightYAxis = {};

		var chartLines = $('#chartConfigArea tr:gt(0)', target);
		chartConf.chartLineParams = [];
		chartLines.each(function(i, n) {
			var $this = $(n);
			var colName = $this.find('select[name="colNames"] option:selected').val();
			var axisName = $this.find('input[name="axisName"]').val();
			var axisOption = $this.find('select[name="axisOption"] option:selected').val();
			chartConf.chartLineParams.push({
				colName: colName,
				axisName: axisName,
				axisOption: axisOption
			});
		});

		chartConf.chartType = $('#chartType option:selected', target).val();

		chartConf.xAxis.colName = $('#xAxis option:selected', target).val();
		chartConf.leftYAxis.name = $('#leftYAxisName', target).val();
		chartConf.isShowRightYAxis = $('#showRightYAxis', target).prop('checked');
		if (chartConf.isShowRightYAxis) {
			chartConf.rightYAxis.name = $('#rightYAxisName', target).val();
		}

		SmartTable.chartConf = chartConf;
	},
	getConfigHtml: function(ele) {
		// 加载函数列表
		$.ajax({
			url: 'table/getDbProcs?returnTypeKey=0',
			async: false,
			type: 'get'
		}).success(function(data) {
			SmartTable.dbProcs = data;
		});

		$.ajax({
			url: 'editor/useArgList/getParamByPageId?pageId=' + pageId,
			async: false,
			type: 'get'
		}).success(function(data) {
			SmartTable.useParamData = data;
		});

		function getUseParamSelect(paramId) {
			var data = SmartTable.useParamData;

			var useParamSelect;
			var dataLen = data.length;
			if (dataLen > 0) {
				useParamSelect = '<select class="my_select">';
				for (var i = 0; i < dataLen; i++) {
					var line = data[i];
					var id = line.id;
					var selected = false;
					if (paramId == id) {
						selected = true;
					}
					useParamSelect += ('<option ' + (selected ? 'selected' : '') + ' value="' + id + '">' + line.argName + '</option>');
				}
				useParamSelect += '</select>';
			}
			return useParamSelect;
		}

		var path = SmartTable.path;
		var target = $(ele);
		$.get(path + 'tab_config.html', function(html) {
			var dbProcs = SmartTable.dbProcs;
			var $html = $(html);
			var $funGroupId = $html.find('#funGroupId');
			var $funsId = $html.find('#funsId');
			var $funBackType = $html.find('#funBackType');
			var $funDisc = $html.find('#funDisc');
			var $selectType = $html.find('input[name="selectType"]');
			var $funArea = $html.find('#funArea');
			var $sqlArea = $html.find('#sqlArea');

			$html.find('#tabQuery').click(function() {
				var funAreaEle = $(this).parents('#funArea');

				SmartTable.getDialogParam(funAreaEle);

				var funId = SmartTable.funId;
				var paramNameVal = SmartTable.paramNameVal;

				$.get('table/getProcTable', {
					pageId: pageId,
					funId: funId,
					paramNameVal: paramNameVal.join(',')
				}).done(function(data) {
					SmartTable.tableData = data;
					SmartTable.dialog.showPage('chartConf');
					SmartTable.previewTable();
					$('body').data(tabId, data);
				}).fail(function() {
					alert('表格查询错误');
				});
			});
			var setGroupId, setFunName;
			if (SmartTable.active == 'double') {
				var funGroupId = SmartTable.funGroupId;
				var funId = SmartTable.funId;
				var getProcs = dbProcs[funGroupId];
				var getProc;
				for (var proc in getProcs) {
					var id = getProcs[proc].id;
					if (funId == id) {
						getProc = getProcs[proc];
						break;
					}
				}
				if (getProc) {
					setGroupId = funGroupId.split('-')[0];
					setFunName = getProc.funname;
				}
			}

			var i = 0;
			var selProcs;
			// 函数组
			for (var dbGroups in dbProcs) {
				var procs = dbProcs[dbGroups];
				var groupId = dbGroups.split('-')[0];
				var groupName = dbGroups.split('-')[1];
				var $option = $('<option value="' + groupId + '">' + groupName + '</option>').data('data', procs);
				if (setGroupId == groupId) {
					$option.attr('selected', 'selected');

					selProcs = procs;
				}
				$funGroupId.append($option);
				if (i == 0) {
					selProcs = procs;
				}
				i++;
			}
			pullFuns(selProcs);

			// 函数
			function pullFuns(procs) {
				var selProc;

				$funsId.children().remove();
				for (var y = 0; y < procs.length; y++) {
					var proc = procs[y];
					var $option = $('<option value="' + proc.funname + '">' + proc.funname + '</option>').data('data', proc);
					if (setFunName == proc.funname) {
						$option.attr('selected', 'selected');
						selProc = proc;
					}
					$funsId.append($option);
					if (y == 0) {
						selProc = proc;
					}
				}
				pullTxt(selProc);
			}


			// 填充返回类型、函数描述等内容,并根据参数判断是否显示参数配置
			function pullTxt(proc) {
				var backTypeName = proc.backName;
				var funDesic = proc.fundesic;
				$funBackType.text(backTypeName);
				$funDisc.text(funDesic);
				showParams(proc);
			}

			function showParams(proc) {
				var paramNameVal = SmartTable.paramNameVal;
				if ($.isArray(paramNameVal)) {
					paramNameVal = paramNameVal.join(',');
				}

				var paramNameValArr = [];
				if (paramNameVal) {
					paramNameValArr = paramNameVal.split(/@|,/);
				}
				var params;
				try {
					params = eval(proc.funparams);
				} catch (e) {
					params = [];
				}
				var $funParamTableBody = $html.find('#funParamTableBody');
				var $paramsArea = $html.find('#paramsArea');

				function getParamId(name) {
					var id = '';
					if (paramNameValArr.length > 0) {
						for (var i = 0; i < paramNameValArr.length; i++) {
							var paramName = paramNameValArr[i * 2];
							if (name == paramName) {
								id = paramNameValArr[i * 2 + 1];
								break;
							}
						}
					}
					return id;
				}

				$funParamTableBody.children().remove();
				if (params.length > 0) {
					$paramsArea.show();
					for (var i = 0; i < params.length; i++) {
						var $tr = $('<tr></tr>')
						var p = params[i];
						var name = p.name;
						var paramId = getParamId(name);

						var useType = p.useType;
						var useTypeName = '--';
						var itemHtml = '';
						switch (useType) {
							case 'text':
								useTypeName = '文本';
								break;
							case 'date':
								useTypeName = '日期 / 时间';
								break;
							case 'station':
								useTypeName = '单站';
								break;
							case 'stations':
								useTypeName = '多站';
								break;
							case 'field':
								useTypeName = '字段名';
								break;
							case 'fields':
								useTypeName = '多字段名';
								break;
							case 'table':
								useTypeName = '表名';
								break;
							case 'tables':
								useTypeName = '多表名';
								break;
							case 'select':
								useTypeName = '单选';
								var data = p.data;
								if (data.indexOf('options:') == 0) {
									var paramData = data.split('options:')[1];
									var paramDataArr = paramData.split(/->|;/);
									itemHtml = '<select class="my_select">';
									for (var i = 0; i < paramDataArr.length; i++) {
										var val = paramDataArr[i];
										if (i % 2 == 0) {
											itemHtml += '<option ' + (val == paramId ? 'selected' : '') + ' value="' + val + '">';
										} else {
											itemHtml += (val + '</option>');
										}
									}
									itemHtml += '</select>';
								}
								break;
						}
						var $tds = '';
						if (itemHtml != '') {
							$tds = $('<td>' + name + '</td><td data-key="' + useType + '">' + useTypeName + '</td>' +
								'<td>' + itemHtml + '</td>');
						} else {
							if (SmartTable.useParamData) {
								$tds = $('<td>' + name + '</td><td data-key="' + useType + '">' + useTypeName + '</td>' +
									'<td>' + getUseParamSelect(paramId) + '</td>');
							} else {
								$tds = $('<td>' + name + '</td><td data-key="' + useType + '">' + useTypeName + '</td>' +
									'<td>参数未配置</td>');
							}
						}
						$tr.append($tds);

						$funParamTableBody.append($tr);
					}
				} else {
					$paramsArea.hide();
				}
			}

			$funGroupId.on('change', function() {
				var procs = $(this.selectedOptions).data('data');
				pullFuns(procs);
				SmartTable.dialog.hidePage('chartConf');
			});
			$funsId.on('change', function() {
				var proc = $(this.selectedOptions).data('data');
				pullTxt(proc);
				SmartTable.dialog.hidePage('chartConf');
			});

			$selectType.on('click', function() {
				var v = this.value;
				if (v == 'sql') {
					$sqlArea.show();
					$funArea.hide();
				} else if (v == 'fun') {
					$sqlArea.hide();
					$funArea.show();
				}
			});
			target.html($html);
		});
	}
}

var smartTableOkSign = false;
CKEDITOR.plugins.add('smarttable', {
	icons: 'smarttable',
	requires: 'widget',
	init: function(editor) {
		CKEDITOR.dialog.add('smarttable', this.path + 'dialogs/smarttable.js');
		SmartTable.path = this.path;

		var cls = 'smarttable-preview';

		function appendChart(target, tabId, tableData, chartConf) {
			tableData = tableData.slice(0);
			var colNames = tableData[0]; // 获得列
			tableData = tableData.slice(1); // 去除列名的数据

			var chartLineParams = chartConf.chartLineParams,
				chartType = chartConf.chartType,
				xAxisColName = chartConf.xAxis.colName,
				leftYAxisName = chartConf.leftYAxis.name,
				isShowRightYAxis = chartConf.isShowRightYAxis,
				rightYAxisName = chartConf.rightYAxis.name;

			// 存放左侧坐标 或 右侧坐标 的所有数据
			var leftYAxisAllDatas = [];
			var rightYAxisAllDatas = [];

			function getColDatas(colIndex, isParseInt, axisOption) {
				var result = [];
				for (var i = 0; i < tableData.length; i++) {
					var ds = tableData[i];
					var d = ds[colIndex];
					if (isParseInt) {
						d = parseFloat(d);
						if (axisOption == 'leftYAxis') {
							leftYAxisAllDatas.push(d);
						} else if (axisOption == 'rightYAxis') {
							rightYAxisAllDatas.push(d);
						}
					}
					result.push(d);
				}
				return result;
			}
			for (var i = 0; i < chartLineParams.length; i++) {
				var chartLineParam = chartLineParams[i];
				var colName = chartLineParam.colName;
				var axisOption = chartLineParam.axisOption;
				var colIndex = colNames.indexOf(colName);
				chartLineParam.colDatas = getColDatas(colIndex, true, axisOption);
			}

			var xAxisColIndex = colNames.indexOf(xAxisColName);
			chartConf.xAxis.colDatas = getColDatas(xAxisColIndex, false);

			function getMaxMin(allDatas, axis) {
				var min = Math.min.apply(null, allDatas);
				var max = Math.max.apply(null, allDatas);
				max = max + ((max - min) * 0.2);

				axis.min = min;
				axis.max = parseFloat(max.toFixed(2));
			}

			if (leftYAxisAllDatas.length > 0) {
				getMaxMin(leftYAxisAllDatas, chartConf.leftYAxis);
			}
			if (rightYAxisAllDatas.length > 0) {
				getMaxMin(rightYAxisAllDatas, chartConf.rightYAxis);
			}

			var chartOption = newLineExtend(chartConf);
			var chartArea = $(target.findOne('.simplebox-content').$);
			chartArea.css('width','98.5%').css('height', '400px');
			chartArea.children().remove();
			chart = echarts.init(chartArea[0]);
			chart.setOption(chartOption);
		}

		function appendTable(target, tabId) {
			var contentArea = target.findOne('.simplebox-content');
			if (contentArea.getChildCount() != 0) {
				for (var i = 0; i <= contentArea.getChildCount(); i++) {
					var node = contentArea.getChild(0);
					node.remove();
				}
			}

			function getTabHtml(data) {
				jQuery.jsontotable(data, {
					id: "#" + tempTableArea,
					header: true
				});
				var tableArea = jQuery('#' + tempTableArea);
				var table = tableArea.children().attr('id', tabId);
				table.addClass('stripe');
				table.css('font-size', '12px;');
				table.css('line-height', '1.5;');
				table.css('height', SmartTable.tabHeight + 'px');
				tableArea.children().remove();

				setTimeout(function() {
					contentArea.appendHtml(table[0].outerHTML);
					ck.util.builTableData(tabId, SmartTable.tabHeight, editor.document.$);
				}, 50)
			}

			if (!SmartTable.tableData) {
				var funId = SmartTable.funId;
				var paramNameVal = SmartTable.paramNameVal;
				if ($.isArray(paramNameVal)) {
					paramNameVal = paramNameVal.join(',');
				}
				ck.util.sendAjax({
					url: 'table/getProcTable',
					data: {
						pageId: pageId,
						funId: funId,
						paramNameVal: paramNameVal
					}
				}, function(data) {
					// getTabHtml(data.result);					
					$('body').data(tabId, data);
				}, function() {
					ck.util.showMsg(3, '表格查询错误');
				});
			} else {
				var tableData = SmartTable.tableData;
				// getTabHtml(tableData.result);
				// delete SmartTable.tableData;
			}
		}

		editor.widgets.add('smarttable', {
			button: '插入表格',
			dialog: 'smarttable',
			draggable: false,
			requiredContent: 'div(simplebox)',
			template: '<div class="simplebox ' + cls + '"><div class="simplebox-content"></div></div>',
			init: function() {
				this.once('ready', function() {
					if (this.data.isLoad == 1) {
						var element = this.element;

						var tabId = element.data('tabid');
						SmartTable.funId = element.data('fun_id');
						SmartTable.paramNameVal = element.data('param_name_val');
						SmartTable.funGroupId = element.data('fun_group_id');


						appendTable(this.element, tabId)


						// 设置为0，避免 ctrl+z 会再次执行
						this.setData('isLoad', 0);
					}
				});
				// 打开窗口事件
				this.on('doubleclick', function(evt) {
					var element = this.element;
					SmartTable.funId = element.data('fun_id');
					SmartTable.paramNameVal = element.data('param_name_val');
					SmartTable.funGroupId = element.data('fun_group_id');
					SmartTable.chartConf = JSON.parse(decodeURIComponent(element.data('chart_conf')));
					var tabId = element.data('tabid');

					SmartTable.tableData = $('body').data(tabId);

					SmartTable.active = 'double';
				}, null, null, 5);
				// 关闭窗口
				this.on('data', function() {
					if (smartTableOkSign) {
						var element = this.element;
						var tabId = element.data('tabid');
						if (!tabId) {
							tabId = "tabId_" + new Date().valueOf();
							element.data('tabid', tabId);
						}

						element.data('fun_group_id', SmartTable.funGroupId);
						element.data('fun_id', SmartTable.funId);
						element.data('param_name_val', SmartTable.paramNameVal);
						element.data('chart_conf', encodeURIComponent(JSON.stringify(SmartTable.chartConf)));

						appendTable(element, tabId);

						appendChart(element, tabId, SmartTable.tableData.result, SmartTable.chartConf);
					}
				});
			},
			upcast: function(el, data) {
				if (el.name == 'div' && el.hasClass(cls)) {
					// 标记此元素为页面加载的元素
					data.isLoad = 1;
					return el;
				}
			}
		});
	}
});